<template>
  <div class="log-panel-container">
    <div class="log-header">
      <h3>日志</h3>
    </div>

    <div class="log-list">
      <!-- 置顶日志固定在顶部 -->
      <div
        class="top-logs-container"
        v-if="logStore.viewData.filter((log) => log.isTop).length > 0"
      >
        <div
          v-for="(log, index) in logStore.viewData.filter((log) => log.isTop)"
          :key="`top-${index}`"
          class="log-item log-top"
          :class="`log-${log.type}`"
          @dblclick="logStore.readTopLog(log)"
        >
          <div v-if="log.type !== 'pokémon'">
            <div class="log-time" v-if="log.time">{{ log.time }}</div>
            <div class="log-content" v-html="log.content"></div>
          </div>
          <!-- 野生宝可梦卡片 -->
          <div v-else class="pokemon-card">
            <div class="log-time" v-if="log.time">{{ log.time }}</div>
            <div class="log-content" v-html="log.content"></div>
            <div class="catch-button" :class="{ 'is-catching': isCatching }">
              <Icon :name="'ball.svg'" class="catch-icon" />
              <span v-show="!isCatching" @click.stop="catchPokemon(log)"
                >前往捕捉</span
              >
              <span v-show="!isCatching" @click.stop="runAway(log)"
                >赶跑TA!</span
              >
              <span
                v-show="isCatching"
                class="probability-display"
                :class="{
                  'probability-low': currentProbability < 40,
                  'probability-medium':
                    currentProbability >= 40 && currentProbability < 70,
                  'probability-high': currentProbability >= 70,
                }"
              >
                <NumberRoll
                  :number="currentProbability"
                  :min-digits="2"
                  :transition-time="300"
                />%
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 普通日志 -->
      <div class="normal-logs-container">
        <div
          v-for="(log, index) in logStore.viewData.filter((log) => !log.isTop)"
          :key="`normal-${index}`"
          class="log-item"
          :class="`log-${log.type}`"
        >
          <div class="log-time" v-if="log.time">{{ log.time }}</div>
          <div class="log-content" v-html="log.content"></div>
        </div>
        <div v-if="!logStore.viewData.length" class="no-logs">暂无日志信息</div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { useLogStore } from '@/store/log'
import { ref, onMounted } from 'vue'
import { usePokemonStore } from '@/store/pokémonWild'
import { Log } from '@/types/log'
import NumberRoll from '@/components/NumberRoll.vue'
import { useCapturedPokemonStore } from '@/store/capturedPokemon'

const TIME_INTERVAL = 1000

const logStore = useLogStore()
const pokemonStore = usePokemonStore()
const capturedPokemonStore = useCapturedPokemonStore()

// 是否正在捕捉
const isCatching = ref(false)
// 当前捕捉概率
const currentProbability = ref(0)

// 失败次数
const failCount = ref(0)

const catchPokemon = async (log: Log) => {
  // 设置捕捉状态为true
  isCatching.value = true
  currentProbability.value = 0

  const _pokemon = window.$poketmon.getDataById(log.pokemonConfig?.id)

  const initialProbability = pokemonStore.calculateCatchProbability(
    log.pokemonConfig?.id,
    log.pokemonConfig?.action.catchDifficultyEffect
  )

  await new Promise((resolve) => setTimeout(resolve, TIME_INTERVAL))
  const result = await checkCatchSuccess(initialProbability, 1, log)
  // await new Promise((resolve) => setTimeout(resolve, TIME_INTERVAL))

  console.log('捕捉结果:', result ? '成功' : '失败')
  if (result) {
    logStore.updateLog(log.id, {
      type: 'success',
      content: `好耶！捕捉到${pokemonStore.getPokemonName(_pokemon?.name, _pokemon?.uiView)}了！`,
      isTop: false,
    })
    pokemonStore.resumeUpdate()
    capturedPokemonStore.capturePokemon(_pokemon)
    failCount.value = 0
  } else {
    pokemonStore.updateAction(log.id, log.pokemonConfig?.id)
    failCount.value++

    // 结合失败次数计算逃跑概率
    const runAwayProbability =
      ((1 - initialProbability) * Math.pow(10, failCount.value - 1)) / 10
    if (Math.random() <= runAwayProbability) {
      console.log('逃跑概率:', runAwayProbability, '逃跑啦')
      logStore.updateLog(log.id, {
        type: 'error',
        content: `${pokemonStore.getPokemonName(_pokemon?.name, _pokemon?.uiView)}逃跑了！`,
        isTop: false,
      })
      pokemonStore.resumeUpdate()
      isCatching.value = false
      failCount.value = 0
    }
  }
}

const runAway = (log: Log) => {
  console.log('赶跑TA！')
  const _pokemon = window.$poketmon.getDataById(log.pokemonConfig?.id)
  logStore.updateLog(log.id, {
    type: 'error',
    content: `${pokemonStore.getPokemonName(_pokemon?.name, _pokemon?.uiView)}被赶走了！TA的眼神似乎充满了幽怨...`,
    isTop: false,
  })
  pokemonStore.resumeUpdate()
  isCatching.value = false
  failCount.value = 0
}

// 检查捕捉是否成功的函数
const checkCatchSuccess = (
  probability: number,
  attempt: number,
  log: Log
): Promise<boolean> => {
  return new Promise((resolve, reject) => {
    try {
      // 更新当前概率显示
      currentProbability.value = Math.round(probability * 100)

      // 生成0-1之间的随机数
      const randomValue = Math.random()

      // 判断是否在概率范围内
      if (randomValue <= probability) {
        // 在概率范围内，继续下一次判断
        if (attempt < 3) {
          const remainingSpace = 1 - probability
          const increase = Math.random() * remainingSpace
          const newProbability = probability + increase

          setTimeout(() => {
            checkCatchSuccess(newProbability, attempt + 1, log)
              .then(resolve)
              .catch(reject)
          }, TIME_INTERVAL)
        } else {
          // 三次都成功，捕捉成功
          setTimeout(() => {
            isCatching.value = false
            currentProbability.value = 0
            resolve(true) // 捕捉成功
          }, TIME_INTERVAL)
        }
      } else {
        // 不在概率范围内，捕捉失败
        setTimeout(() => {
          isCatching.value = false
          currentProbability.value = 0
          resolve(false) // 捕捉失败
        }, TIME_INTERVAL)
      }
    } catch (error) {
      console.log(error)
      reject(error)
    }
  })
}

onMounted(() => {
  logStore.initData()
})
</script>
<style lang="less" scoped>
@time-interval: 1000ms;

.log-panel-container {
  color: #fff;
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20px 10px 15px 10px;
  background-color: rgba(0, 0, 0, 0.1);
  border-radius: 6px;
  --time-interval: 1000ms; // 添加CSS变量定义

  .log-header {
    padding: 5px 12px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 500;
    }
  }

  .log-list {
    flex: 1;
    position: relative;
    background-color: rgba(255, 255, 255, 0.05);
    border-radius: 6px;
    margin-top: 0px;
    box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.2);
    padding-bottom: 5px;
    transform: translateY(0);
    height: 80%;

    display: flex;
    flex-direction: column;

    .top-logs-container {
      z-index: 10;
      padding: 8px 8px 0;
    }

    .normal-logs-container {
      padding: 8px;
      overflow-y: scroll;
      flex: 1;

      &::-webkit-scrollbar {
        width: 4px;
      }

      &::-webkit-scrollbar-track {
        background: rgba(0, 0, 0, 0.1);
      }

      &::-webkit-scrollbar-thumb {
        background: rgba(255, 255, 255, 0.3);
        border-radius: 2px;
      }
    }
  }

  .log-item {
    padding: 8px 12px 8px 12px;
    margin-bottom: 8px;
    border-radius: 6px;
    background-color: rgba(0, 0, 0, 0.2);
    border-left: 3px solid #666;
    transition: all 0.2s ease;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

    &:hover {
      background-color: rgba(0, 0, 0, 0.3);
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
    }

    .log-time {
      font-size: 12px;
      color: rgba(255, 255, 255, 0.6);
      margin-bottom: 5px;
    }

    .log-content {
      word-break: break-word;
    }
  }

  .log-normal {
    border-left-color: #666;
  }

  .log-error {
    border-left-color: #ff4d4f;
  }

  .log-warning {
    border-left-color: #faad14;
  }

  .log-success {
    border-left-color: #52c41a;
  }

  .log-pokémon {
    border-left-color: #1890ff;
  }

  .log-top {
    background-color: rgba(30, 30, 30, 0.8);
    border-left-width: 5px;
    border-radius: 8px;
    padding: 6px 14px 10px 14px;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.5);
    position: relative;
    margin-bottom: 4px;
    cursor: pointer;

    &::before {
      content: '';
      position: absolute;
      top: 0;
      right: 0;
      width: 0;
      height: 0;
      border-style: solid;
      border-width: 0 16px 16px 0;
      border-color: transparent rgba(255, 255, 255, 0.4) transparent transparent;
    }

    &:hover {
      background-color: rgba(40, 40, 40, 0.9);
      box-shadow: 0 6px 18px rgba(0, 0, 0, 0.6);
      transform: translateY(-1px);
    }

    .log-time {
      font-weight: 500;
      color: rgba(255, 255, 255, 0.9);
    }

    .log-content {
      font-weight: 500;
      color: rgba(255, 255, 255, 0.95);
    }

    &::after {
      content: '';
      position: absolute;
      bottom: -6px;
      left: 0;
      right: 0;
      height: 6px;
      background: linear-gradient(to bottom, rgba(0, 0, 0, 0.3), transparent);
    }
  }

  .pokemon-card {
    overflow: hidden;

    .catch-button {
      position: absolute;
      bottom: 8px;
      left: -100%;
      top: -1px;
      background: rgba(0, 0, 0, 0.75);
      color: #fff;
      padding: 6px 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 10px; // 增加间距
      cursor: pointer;
      transition:
        left 0.3s ease,
        opacity 0.3s ease,
        transform 0.3s ease;
      width: 100%;
      height: 100%;
      border-radius: 4px;
      font-size: 14px;
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
      opacity: 0;
      pointer-events: none;
      transform: scale(0.9);

      // 捕捉状态下增加内边距
      &.is-catching {
        padding: 6px 15px; // 增加水平内边距
      }

      .catch-icon {
        font-size: 16px;
      }

      span {
        cursor: pointer;

        &:hover {
          text-decoration: underline;
        }
      }

      .probability-display {
        margin-left: 10px;
        font-size: 18px;
        font-weight: bold;
        text-decoration: none;
        text-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
        display: flex;
        align-items: center;

        :deep(.number-roll-container) {
          margin-right: 2px; // 添加右边距，与%符号保持距离

          .digit-container {
            // 移除宽度限制，使用组件内的设置
          }

          // 移除digits-3特殊处理，使用组件内的设置
        }

        &.probability-low {
          color: #ff4d4f; // 红色

          :deep(.digit) {
            color: #ff4d4f;
          }
        }

        &.probability-medium {
          color: #faad14; // 黄色

          :deep(.digit) {
            color: #faad14;
          }
        }

        &.probability-high {
          color: #52c41a; // 绿色

          :deep(.digit) {
            color: #52c41a;
          }
        }
      }

      &:hover {
        :deep(.catch-icon) {
          animation: rotate-icon 1.5s ease-in-out;
          animation-iteration-count: infinite;
          animation-delay: 0.3s;
        }
      }

      // 捕捉状态的样式
      &.is-catching {
        opacity: 1;
        left: 0;
        top: 0;
        pointer-events: auto;
        transform: scale(1);

        .catch-icon {
          font-size: 24px; // 图标变大
          // 循环播放
          animation: shake-ball var(--time-interval) ease-in-out infinite; // 增加动画持续时间到2秒
          // animation间隔1秒
          animation-delay: var(--time-interval);
        }
      }
    }

    &:hover {
      .catch-button {
        left: 0px;
        top: 0px;
        opacity: 1;
        pointer-events: auto;
        transform: scale(1);
      }
    }
  }

  @keyframes rotate-icon {
    0% {
      transform: rotate(0deg);
    }
    40% {
      transform: rotate(360deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }

  // 添加摇晃动画
  @keyframes shake-ball {
    0%,
    80% {
      transform: translateX(0);
    }
    20% {
      transform: translateX(-5px) rotate(-10deg);
    }
    60% {
      transform: translateX(5px) rotate(10deg);
    }
  }

  .no-logs {
    text-align: center;
    color: rgba(255, 255, 255, 0.4);
    padding: 20px 0;
    font-size: 14px;
  }
}
</style>
